package com.xinqi.modules.sys.dict.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xinqi.common.base.error.CommonErrors;
import com.xinqi.common.base.response.PageInfo;
import com.xinqi.common.base.response.Param;
import com.xinqi.common.base.utils.tree.TreeHelp;
import com.xinqi.common.mybatis.utils.Pages;
import com.xinqi.common.mybatis.utils.Queries;
import com.xinqi.modules.sys.dict.convert.DictDataConvert;
import com.xinqi.modules.sys.dict.domain.DictDataEntity;
import com.xinqi.modules.sys.dict.dto.req.DictDataCreateDTO;
import com.xinqi.modules.sys.dict.dto.req.DictDataDeleteDTO;
import com.xinqi.modules.sys.dict.dto.req.DictDataQueryDTO;
import com.xinqi.modules.sys.dict.dto.req.DictDataUpdateDTO;
import com.xinqi.modules.sys.dict.dto.rsp.DictDataResultDTO;
import com.xinqi.modules.sys.dict.manager.DictDataManager;
import com.xinqi.modules.sys.dict.service.DictDataService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.validation.Valid;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 字典数据表服务层实现
 *
 * @author: linkai
 * @date: 2023/05/21
 */
@Validated
@Service("dictDataService")
@RequiredArgsConstructor
public class DictDataServiceImpl implements DictDataService {
    private final DictDataConvert dictDataConvert;
    private final DictDataManager dictDataManager;

    /**
     * 分页查询 字典数据表数据
     */
    @Override
    @DS("slaver")
    public PageInfo<DictDataResultDTO> page(Param pageable, DictDataQueryDTO query) {
        IPage<DictDataEntity> page = dictDataManager.page(Pages.page(pageable), wrapper(query));
        return Pages.convert(page, dictDataConvert::convert);
    }

    /**
     * 查询 字典数据表数据
     */
    @Override
    public List<DictDataResultDTO> find(DictDataQueryDTO query) {
        return dictDataManager.list(wrapper(query)).stream()
            .map(dictDataConvert::convert).collect(Collectors.toList());
    }

    private LambdaQueryWrapper<DictDataEntity> wrapper(DictDataQueryDTO query) {
        LambdaQueryWrapper<DictDataEntity> wrapper = Queries.lambda();
        Queries.accept(query.getId(), v -> wrapper.eq(DictDataEntity::getId, v));
        Queries.accept(query.getDictType(), v -> wrapper.eq(DictDataEntity::getDictType, v));
        Queries.accept(query.getDictKey(), v -> wrapper.eq(DictDataEntity::getDictKey, v));
        return wrapper;
    }

    /**
     * 根据id查询 字典数据表数据
     */
    @Override
    public DictDataResultDTO findById(Long id) {
        CommonErrors.BAD_REQUEST.check(Objects.nonNull(id), "ID不能为空");
        return Optional.ofNullable(dictDataManager.findById(id)).map(dictDataConvert::convert).orElse(null);
    }

    /**
     * 新增 字典数据表数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long insert(@Valid DictDataCreateDTO dto) {
        DictDataEntity entity = dictDataConvert.create(dto);
        dictDataManager.save(entity);
        return entity.getId();
    }

    /**
     * 根据id修改 字典数据表数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateById(@Valid DictDataUpdateDTO dto) {
        Optional.ofNullable(dictDataManager.getById(dto.getId()))
            .orElseThrow(() -> CommonErrors.BAD_REQUEST.asException("数据不存在"));
        DictDataEntity entity = dictDataConvert.update(dto);
        return dictDataManager.updateById(entity);
    }

    /**
     * 根据id删除 字典数据表数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteById(Long id) {
        CommonErrors.BAD_REQUEST.check(Objects.nonNull(id), "ID不能为空");
        return dictDataManager.removeById(id);
    }

    /**
     * 根据id删除 字典数据表数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteById(DictDataDeleteDTO dto) {
        return deleteById(dto.getId());
    }

    @Override
    public List<DictDataResultDTO> treeList(DictDataQueryDTO dto) {
        List<DictDataResultDTO> list = find(dto);
        if (CollectionUtils.isEmpty(list)) {
            return Collections.emptyList();

        }

        List<DictDataResultDTO> tree = TreeHelp.<DictDataResultDTO, Long>builder()
            .setList(list)
            .setChildren("children")
            .setParent("pid")
            .build()
            .handle(0L);
        return tree;
    }

}
